var APP = require("../../../lib/main/app");
var Config = require("../../../lib/config/config");
var USER = require("../../../lib/module/user");
var page = {
	type: null, //考试科目
	videoObj: null, //视频信息
	videoCategoryId: null, //科目id 视频
	keyupCount: 0,
	subject: null, //科目列表
	categoryId: null, //科目id
	examData: null, //当前用户可考的科目
	examId: 0,
	socketManager: null,
	sid: '', //通信id
	sign: '',
	arrIndex: 1,
	timing: null,
	startTime: 0, //开始时间
	endTime: 0, //结束时间
	mSuccess: [0, 0, 0, 0, 0, 0], //其它模块成功次数
	mirrorSuccess: [0, 0, 0, 0, 0, 0], //镜下识别成功次数
	successNum: 0, //成功失败数量
	errorTimes: 0,//移圈触碰铁丝次数
	leftErrorTimes: 0,//左手移圈触碰铁丝次数
	rightErrorTimes: 0,//右手移圈触碰铁丝次数
	typeName: '', //分类名称
	type: null, //分类code
	metalBall: 0, //红色球
	plasticBall: 0, //绿色球
	serialPort: null, //串口模块
	serialPortInfo: {
		path: "COM3",
		baudRate: 115200
	},
	deviceArr: [], //设备列表
	isRoomController: false,
	equipmentTime: null,
	instruct: [], //发送设备指令
	switch_state: 'wait',//当前状态
	isError: false,//是否有错
	threadError: false,//是否触发错误
	threadTrigger: false,//记录飞越龙门是否开始
	rightNum: 0,//是否有错
	isOrder: true,//是否有顺序
	ballCensus: true,//限制短时间增加次数
	metalBallCensus: true,//限制短时间增加次数
	serialPortListen: null, //定时监测串口连接状态
	useTimes: 0,//使用时间
	shearcensus: true,//剪切统计
	isEnterTest: false,//是否进入了考试页面
	lang: 'cn',
	browser: null,//浏览器
	hand: '',//操作部位
	userInfo: null,//用户信息
	visPlugin: null,//会议模块
	deviceId:'',//设备序列号
	ready: function () {
		var that = this;
		that.hand = '';//操作部位左手还是右手
		that.browser = api.require('webBrowser');
		that.visPlugin = api.require('visPlugin')

		// that.browser.init(function(ret,_err){
		// 	that.browser.loadUrl({
		// 		url: 'https://www.weiyipro.com/h5-pc/#/login?token=cMvaFKIdEoWdmN8dJL1gssw7aV0NfHxizGMXZz6XkXl1WOKA3IqgnmSZ7ipBFxfsCJ%2BRyTsiN3QjLdYSzr%2B%2BloeOfH%2FPJhkTz6skC6HFvmk%3D'
		// 	});
		// });
		that.deviceId = api.deviceId; //设备序列号
		// console.log('deviceId',deviceId)

		try {
			let lang = api.getGlobalData({ key: 'lang' }) || 'cn';
			that.lang = lang;
			i18n("[i18n]", {
				lang: lang,// 变更语言
				filePath: "i18n/",
				get: true
			});
		} catch (e) {
			//TODO handle the exception
		}
		that.socketManager = api.require('socketManager');
		that.serialPort = api.require("fvvSerialPort"); //串口模块
		// 头部处理
		var headerHeight = $('#header').height();
		$('body').css('padding-top', headerHeight);
		that.initData();
	},
	on: function () {
		var that = this;

		clearInterval(that.timing);
		// 登录成功
		api.addEventListener({
			name: 'LOGIN_SUCCESS'
		}, function (ret, err) {
			that.getUserinfo(); // 获取用户信息
		});
		// 监听是否进入了考试页面
		api.addEventListener({
			name: 'isEnterTest'
		}, function (ret, err) {
			// console.log('isEnterTest',ret.value.isEnterTest)
			that.isEnterTest = ret.value.isEnterTest;
		});
		// 监听到时间结束考试
		api.addEventListener({
			name: 'time_end'
		}, function (ret, err) {
			that.countScore(); //计算得分
			that.switch_state = 'close';
		});
		// 考试完成
		api.addEventListener({
			name: 'TEST_OVER'
		}, function (ret, err) {
			clearInterval(that.timing);
			// console.log('结束结束');
			that.getNewestExamLog();
			that.arrIndex = 1;
		});
		// 上报成绩后刷新考试结果
		api.addEventListener({
			name: 'Newest_ExamLog'
		}, function (ret, err) {
			that.getNewestExamLog();
		});
		// 使用时间
		api.addEventListener({
			name: 'useTimes'
		}, function (ret, err) {
			that.useTimes = ret.value.useTimes;
		});
		//批量事件start
		var events = [
			//切换科目
			['#nav-box li', function () {
				var _id = $(this).data('id');
				if (that.videoCategoryId == _id) {
					return false;
				}
				$(this).addClass('active').siblings().removeClass('active');
				that.videoCategoryId = _id;
				try {
					var videos = document.getElementsByTagName('video');
					videos[0].pause();
				} catch (e) {
					//TODO handle the exception
				}
				that.getVideoList(); //重新加载视频
				that.rules(); //重新规则相关内容
			}],
			// 退出确认框
			['.exitBtn', function () {
				try {
					var videos = document.getElementsByTagName('video');
					videos[0].pause();
				} catch (e) {
					//TODO handle the exception
				}
				$('.index-tc').show();
			}],
			// 关闭弹窗
			['.index-tc .close', function () {
				$('.index-tc').hide();
			}],
			// 确认退出
			['#exitBtn', function () {
				$('.index-tc').hide();
				that.exitBtn();
			}],
			// 打开搜索设备弹窗
			['.device', function () {
				let text = $(this).find('span').text();
				let toast = i18n.get("reselect") || '请退出登录后重新选择';
				if ((that.lang == 'cn' && text != '请选择') || (that.lang == 'en' && text != 'Please select')) {
					API.errorToast(toast);
					return false;
				}

				if (!that.isRoomController) {
					that.isRoomController = true;
					that.roomController(); //打开udp通信
				}
				clearTimeout(that.equipmentTime);
				that.deviceArr = []; //重置列表数据
				that.instruct = []; //重置数据
				$('.equipment-lis-box').html('');
				$('.equipment').addClass('equipment-load-show');
				that.equipmentTime = setTimeout(function () {
					$('.equipment').removeClass('equipment-load-show');
				}, 10000)
				$('.equipment').show();
			}],
			// 关闭搜索设备弹窗
			['.close-equipment', function () {
				$('.equipment').hide();
			}],
			// 选择设备
			['.equipment-lis', function () {
				var instructCode = $(this).data('code');
				that.sendCmd(String(instructCode)); //发送数据
				$('.device span').text($(this).text());
				$('.equipment').hide();
			}],
			// 重新搜索
			['.reset-btn', function () {
				clearTimeout(that.equipmentTime);
				$('.equipment').addClass('equipment-load-show');
				that.deviceArr = []; //重置列表数据
				that.instruct = []; //重置数据
				$('.equipment-lis-box').html('');
				that.closeSocket(); //关闭udp通信
				that.roomController(); //重连udp通信
				that.equipmentTime = setTimeout(function () {
					$('.equipment').removeClass('equipment-load-show');
				}, 10000)
			}],
			// 开始会议
			['.meeting-btn', function () {
				let serial = $('.meeting .serial').val();
				let nickName = that.userInfo.nickname
				let meetingName = that.userInfo.hospital_name
				let toast = i18n.get("serial.empty") || '会议号/邀请码不能为空！';
				if(!serial){
					API.errorToast(toast);
					return;
				}
				$('.meeting').hide();
				that.enterMeeting(serial,nickName,meetingName,false)
			}],
			['.close-meeting', function () {
				$('.meeting').hide();
			}],
			// 打开页面
			['.openPage', function () {
				var url = $(this).data('url');
				var _index = $(this).data('index');
				var _type = $(this).data('type');
				var code = that.type; //项目编号
				var typeName = that.typeName; //项目名称
				try {
					var videos = document.getElementsByTagName('video');
					videos[0].pause();
				} catch (e) {
					//TODO handle the exception
				}

				// 加入会议
				if (_type == 'joinMeeting') {
					$('.meeting').show();
					return;
				}
				// 快速进入会议
				if (_type == 'fastJoinMeeting') {
					let nickName = that.userInfo.nickname
					let meetingName = that.userInfo.hospital_name
					// 获取会议号
					APP.r.get({
						api: 'meeting/checkDevice',
						params: {
							device_sn: that.deviceId,//设备序列号
						},
						success: function (res) {
							if(res.data.length > 0 || res.data.meeting_no){
								that.enterMeeting(res.data.meeting_no,nickName,meetingName,true)
							}else{
								API.errorToast('未绑定设备请联系管理员');
							}
						}
					});
					return;
				}

				// that.browser.open({
				// 	url: 'https://www.weiyipro.com/h5-pc/#/login?token=cMvaFKIdEoWdmN8dJL1gssw7aV0NfHxizGMXZz6XkXl1WOKA3IqgnmSZ7ipBFxfsCJ%2BRyTsiN3QjLdYSzr%2B%2BloeOfH%2FPJhkTz6skC6HFvmk%3D'
				// });
				// that.browser.openView({
				// 	url: 'https://www.weiyipro.com/h5-pc/#/login?token=cMvaFKIdEoWdmN8dJL1gssw7aV0NfHxizGMXZz6XkXl1WOKA3IqgnmSZ7ipBFxfsCJ%2BRyTsiN3QjLdYSzr%2B%2BloeOfH%2FPJhkTz6skC6HFvmk%3D',//https://www.weiyipro.com/h5-mobile/#/login?token=cMvaFKIdEoWdmN8dJL1gssw7aV0NfHxizGMXZz6XkXkxwX3P%2FTLcNpDYuiYW17jTLo%2Fk%2BU7SNL9B379EbyyCFxA0jXRWc5qRy2bi3KnSK1A%3D
				// 	rect: {
				// 		x: 0,
				// 		y: 64,
				// 		w: 'auto',
				// 		h: 'auto'
				// 	}
				// }, function(ret, err) {
				if (_index == 1) {
					var _id = that.videoCategoryId;
					APP.w.openWin(url, {
						id: _id,
						code: code,
						typeName: typeName
					})
				} else if (_index == 3) {
					// 考试与训练
					if (_type == 'test') {
						let msg = i18n.get("data.loading") || '数据正在加载中，请稍等...';
						// 判断有无加载完模块
						if (!that.type) {
							api.toast({
								msg: msg,
								duration: 2000,
								location: 'bottom'
							});
							return;
						}
						// 考试 判断有无可考试的项目
						that.getExam({
							success: function () {
								APP.w.openWin(url, {
									categoryId: that.categoryId,
									deviceId: _type,
									examId: that.examId,
									code: code,
									typeName: typeName
								})
							},
							fail: function () {

							}
						}); // 获取当前用户可参加考试的科目
					} else {
						// 判断有无加载完模块
						if (!that.type) {
							let msg = i18n.get("data.loading") || '数据正在加载中，请稍等...';
							api.toast({
								msg: msg,
								duration: 2000,
								location: 'bottom'
							});
							return;
						}
						// 模拟
						that.examId = 0;
						APP.w.openWin(url, {
							categoryId: that.categoryId,
							deviceId: _type,
							examId: that.examId,
							code: code,
							typeName: typeName
						})
					}

				} else {
					APP.w.openWin(url, {
						code: code,
						typeName: typeName
					})
				}
			}],

		];
		APP.e.more(events);
		//批量事件end
		//首页点击返回
		API.listenEvt('keyback', function () {
			try {
				var videos = document.getElementsByTagName('video');
				videos[0].pause();
			} catch (e) {
				//TODO handle the exception
			}
			if (that.keyupCount == 0) {
				let msg = i18n.get("exit.app") || '再点一次退出应用';
				api.toast({
					msg: msg,
					duration: 2000,
					location: 'bottom'
				});
				that.keyupCount = 1;
			} else if (that.keyupCount == 1) {
				api.closeWidget({
					silent: true
				});
			}
		});
	},
	methods: {
		enterMeeting:function(serial,nickName,meetingName,freeMark){
			var that = this;
			APP.r.get({
				api: 'meeting/check',
				params: {
					meeting_no: serial
				},
				success: function (res) {
					if(res.data.result){
						meetingName = res.data.meeting && res.data.meeting.title ? res.data.meeting.title : meetingName;
						freeMark = true
					}
					// new Date().getTime()
					let userid = serial + '-' + that.userInfo.id;
					let params = {
						url: APP.meetingUrl, // api地址https://n.weiyipro.com:555
						serial, // 会议/会诊号 成都301431417 860606378
						showMDT: false, // 是否是MDT
						nickName, // 用户名
						meetingName: meetingName, // 会议名
						isMeeting: false, // false：这是一个会诊 true 这是一个会议
						conName: meetingName, // 会议名
						userId: userid, // 用户id
						property: JSON.stringify({}), // 保留 先写死
						audio: false,
						video: false,
						freeMark //是否开启标注
					}
					console.log('params',JSON.stringify(params))
					that.visPlugin.joinMeeting(params)
				}
			});
		},
		// 加载数据
		initData: function () {
			var that = this;
			that.getCategoryList(); //获取分类
			that.getNewestExamLog(); // 获取最新考试信息
			that.getUserinfo(); // 获取用户信息

			setTimeout(function () {
				that.getDeviceList(); //串口设备列表
				that.getDevicePath(); //打开串口

			}, 3000)
		},
		// 串口相关开始
		// 重置数据
		resetData: function () {
			var that = this;
			that.isEnterTest = false;
			that.switch_state = 'wait';//当前状态
			that.startTime = 0;//开始时间
			that.endTime = 0;//结束时间
			that.mSuccess = [0, 0, 0, 0, 0, 0];//其它模块成功次数
			that.mirrorSuccess = [0, 0, 0, 0, 0, 0]; //镜下识别成功次数
			that.successNum = 0;//成功失败数量
			that.errorTimes = 0;//移圈触碰铁丝次数
			that.leftErrorTimes = 0;//左手移圈触碰铁丝次数
			that.rightErrorTimes = 0;//右手移圈触碰铁丝次数
			that.metalBall = 0;//红色球
			that.threadError = false;//是否触发错误
			that.threadTrigger = false;//记录飞越龙门是否开始
			that.plasticBall = 0;//绿色球
			that.isError = false;//是否有错
			that.rightNum = 0;//是否有错
			that.isOrder = true;//是否有顺序
			that.useTimes = 0;
			that.hand = '';//操作部位左手还是右手
		},
		//获取串口设备列表，示例，本项目没有用上
		getDeviceList: function () {
			var that = this;
			//同步串口设备列表
			// var list = that.serialPort.getAllDeviceListSync().list
			// console.log(JSON.stringify(list))
			//异步串口设备列表
			that.serialPort.getAllDeviceList(function (ret) {
				console.log('串口设备列表：' + JSON.stringify(ret.list))
			})
		},
		//获取串口路径列表
		getDevicePath: function () {
			var that = this;
			//同步获取串口路径
			// this.deviceList = that.serialPort.getAllDevicePathSync().list
			//异步获取串口路径
			that.serialPort.getAllDevicePath(function (ret) {
				console.log('获取串口路径：' + JSON.stringify(ret.list))
				var serialPortInfo = [];
				for (var i = 0; i < ret.list.length; i++) {
					if (ret.list[i].indexOf("USB") != -1) {
						serialPortInfo.push(i)
					}
				}
				if (serialPortInfo.length > 1) {
					that.serialPortInfo.path = '/dev/ttyUSB0';
				} else if (serialPortInfo.length == 1) {
					that.serialPortInfo.path = ret.list[serialPortInfo[0]];
				} else {
					that.serialPortInfo.path = ret.list[0]
				}
				that.open(); //打开串口
			})
		},
		//打开串口
		open: function () {
			var that = this;
			//以下可选接口可以不设置
			//设置串口波特率，可选，默认115200
			that.serialPort.setBaudRate(that.serialPortInfo.baudRate);
			//设置数据位，可选，默认8
			that.serialPort.setDataBits(8);
			//设置停止位，可选，默认1
			that.serialPort.setStopBits(1);
			//设置校验，可选，默认0无校验，1奇校验，2偶校验
			that.serialPort.setParity(0);
			//设置流控，可选，默认0不使用流控，1硬件，2软件
			that.serialPort.setFlowCon(0);
			//设置接收消息类型
			that.serialPort.setReceiveType("HEX")
			//打开串口
			console.log(that.serialPortInfo.path) //串口路径/dev/ttyUSB0
			// that.serialPortInfo.path = '/dev/ttyS0' //测试
			if (!that.serialPortInfo.path) {
				return false;
			}
			// that.serialPortInfo.path 测试使用'/dev/ttyS0'
			var state = that.serialPort.open(that.serialPortInfo.path)
			// that.send();//发送数据测试
			console.log('串口连接状态：' + state)
			if (state) {
				that.listenMessage(); //监听串口数据接收
			}
			// 监测串口连接状态
			// if(that.serialPortListen){
			// 	clearInterval(that.serialPortListen)
			// }
			// that.serialPortListen = setInterval(() => {
			// 	let isOpen = that.serialPort.isOpen()
			// 	console.log('连接状态')
			// 	console.log(isOpen)
			// 	if(!that.serialPort.isOpen()){
			// 		console.log('44444444444')

			// 		that.resetSerialPort(); //重连串口
			// 	}
			// },3000)
		},
		// 重连串口
		// resetSerialPort: function() {
		// 	var that = this;
		// 	that.serialPort.close();
		// 	that.switch_state = 'wait';//当前状态
		// 	that.startTime = 0;//开始时间
		// 	that.endTime = 0;//结束时间
		// 	that.mSuccess = [0, 0, 0, 0, 0, 0];//镜下识别成功次数
		// 	that.successNum = 0;//成功失败数量
		// 	that.metalBall = 0;//金属球
		// 	that.plasticBall = 0;//塑料球
		// 	that.type = null;//分类
		// 	that.isError = false;//是否有错
		// 	that.getDeviceList(); //串口设备列表
		// 	that.getDevicePath(); //打开串口
		// },
		//关闭串口
		close: function () {
			var that = this;
			that.serialPort.close()
			this.isOpen = false
		},
		//检查串口是否打开
		checkOpen: function () {
			var that = this;
			this.isOpen = that.serialPort.isOpen()
		},
		//设置接收消息类型
		setReceiveType: function () {
			var that = this;
			that.serialPort.setReceiveType(this.receiveType)
		},
		//设置发送消息类型
		setSendType: function () {
			var that = this;
			that.serialPort.setSendType(this.sendType)
		},
		send: function () {
			var that = this;
			// this.receive += ("<-("+this.sendType+") " + this.sendText + "\n")
			that.serialPort.send('0xaa,0x01,0x0c,0x0a,0xab')
		},
		//监听消息
		listenMessage: function () {
			var that = this;
			api.addEventListener({
				name: "FvvSerialPort"
			}, function (ret) {
				var msg = ret.value
				// console.log('串口接收数据成功：' + JSON.stringify(msg))
				switch (msg.type) {
					case "receive":
						// 接收成功
						// console.log('串口接收数据成功：' + msg.msg)
						that.receiveData(msg.msg); //对接收数据处理
						// that.receive += ("->("+that.receiveType+") " + msg.msg + "\n")
						break;
					default:
				}
			})
		},
		// 串口相关结束

		// 连接硬件通信
		roomController: function () {
			var that = this;
			// var networkAddress = api.require('networkAddress');
			var networkAddress = api.require('visPlugin')
			networkAddress.get(function (ret, err) {
				// 先获取ip地址
				// alert(JSON.stringify( ret.address ))
				console.log(JSON.stringify(ret.address))
				that.socketManager.createSocket({
					type: 'udp',
					udpMode: 'broadcast',
					host: ret.address,
					// host: '192.168.101.56',
					port: 40134,
					localPort: 40134,
					// timeout: 1
				}, function (ret, err) {
					if (ret) {
						var state = ret.state;
						var data = ret.data;
						var stateStr = "";
						that.sid = ret.sid;
						// console.log("sid:" + sid)
						if (101 === state) {
							stateStr = "创建成功";
							// console.log('创建通信....' + JSON.stringify(ret));
						} else if (102 === state) {
							stateStr = "连接成功";
						} else if (103 === state) {
							stateStr = "收到消息";
							that.receiveData(data); //对接收数据处理
						} else if (201 === state) {
							stateStr = "创建失败";
						} else if (202 === state) {
							stateStr = "连接失败";
						} else if (203 === state) {
							stateStr = "异常断开";
						} else if (204 === state) {
							stateStr = "正常断开";
						} else if (205 === state) {
							stateStr = "发生未知错误";
						}
						// var msg = 'sid: ' + that.sid + '\nstate: ' + stateStr + '\ndata: ' + (data ? JSON.stringify(data) : '');
						// console.log(msg);
					} else {
						console.log(JSON.stringify(err));
					}
				});
			});
		},
		// 关闭硬件通信
		closeSocket: function () {
			var that = this;
			that.socketManager.closeSocket({
				sid: that.sid
			}, function (ret, err) {
				if (ret.status) {
					console.log(1)
				} else {
					console.log(2)
				}
			});
		},
		// 发送命令
		sendCmd: function (cmd) {
			var that = this;
			that.socketManager.write({
				sid: that.sid,
				data: cmd
			}, function (ret, err) {
				if (ret.status) {
					console.log('发送消息成功');
				} else {
					console.log('发送消息失败');
				}
			});
		},
		// 接收数据处理
		receiveData: function (data) {
			var that = this;
			// var _tst = '0xaa,0x01,0x0c,0x0a,0xab';
			// 测试调试数据弹窗
			// api.sendEvent({
			// 	name: 'receiveDataOld',
			// 	extra: {
			// 		receiveDataOld: data
			// 	}
			// });

			var _tst = data;
			// var _tst = 'AA030100AE';
			var _data = [];
			// 处理数据
			for (let i = 0; i < 5; i++) {
				_data.push('0x' + _tst.substr(2 * i, 2))
			}
			var _string = '';
			// console.log('_data_data_data_data' + _data)
			// 发送数据大于12字节 属于搜索设备 0xaa,0x01,0x53,0x69,0x6d,0x75,0x6c,0x61,0x74,0x69,0x6f,0x6e
			if (_data.length == 12) {
				var newArr = [];
				newArr[0] = _tst;
				for (var i = 2; i < _data.length; i++) {
					_string += that.hexCharCodeToStr(_data[i]); //十六进制转ASCII码
				}
				if (that.deviceArr.length > 0) {
					var ishave = false;
					for (var i = 0; i < that.deviceArr.length; i++) {
						if (_string == that.deviceArr[i]) {
							ishave = true;
							break;
						}
					}
					if (!ishave) {
						that.deviceArr.push(_string);
						that.instruct.push(newArr);
					}
				} else {
					that.deviceArr.push(_string);
					that.instruct.push(newArr);
				}

				// 加载设备
				var _html = '';
				for (var i = 0; i < that.deviceArr.length; i++) {
					_html += `<div class="equipment-lis" data-code = "${that.instruct[i][0]}">${that.deviceArr[i]}</div>`;
				}
				$('.equipment-lis-box').html(_html);
				return false;
			}
			// 数据处理转二进制
			var newArr = []; //转为2进制后的数据
			for (var i = 0; i < _data.length; i++) {
				// console.log(that.transform(_data[i].substring(2, 4)))
				newArr.push(that.transform(_data[i].substring(2, 4)))
			}
			// 获取校验值
			var checkSum = 0;
			for (var i = 0; i < 4; i++) {
				checkSum += Number(_data[i]);
			}
			// 获取数据1值
			var bitData1 = newArr[2];
			if (bitData1.length < 8) {
				var newstr = String(bitData1);
				for (var i = 0; i < (8 - bitData1.length); i++) {
					newstr = '0' + newstr
				}
				bitData1 = newstr
			}
			var bitUser1 = []; //此数据用来逻辑计算判断
			for (var i = 0; i < bitData1.length; i++) {
				bitUser1.unshift(bitData1[i]);
			}
			// 获取数据2值
			var bitData2 = newArr[3]
			if (bitData2.length < 8) {
				var newstr = String(bitData2);
				for (var i = 0; i < (8 - bitData2.length); i++) {
					newstr = '0' + newstr
				}
				bitData2 = newstr
			}
			var bitUser2 = []; //此数据用来逻辑计算判断
			for (var i = 0; i < bitData2.length; i++) {
				bitUser2.unshift(bitData2[i]);
			}
			// 判断有无镜下识别
			var microscopicData = String(bitData2).split('').reverse();
			var isMicroscopic = microscopicData[0] == 1 ? true : false;
			// 获取当前科目
			that.type = _data[1];
			// 校验成功
			// console.log('校验1:'+(checkSum % 256) )
			// console.log('校验2:'+(Number(_data[4])))
			if ((checkSum % 256) == (_data[4] % 256)) {

				var data1 = String(bitData1).split('').reverse();
				var data2 = String(bitData2).split('').reverse();
				// if(data2[6] == 1){
				// 	console.log('that.hand',that.hand)
				// 	console.log('data2[6]',data2[6])
				// }
				// if(data2[7] == 1){
				// 	console.log('that.hand',that.hand)
				// 	console.log('data2[7]',data2[7])
				// }
				// if(data1[7] == 1){
				// 	console.log('that.hand',that.hand)
				// 	console.log('data1[7]结束+++++++',data1[7])
				// 	console.log('data2[7]结束+++++++',data2[7])
				// 	console.log('data2[6]结束+++++++',data2[6])
				// }	
				// 判断是否换手操作
				if (that.hand && (that.type != '0x03' || isMicroscopic)) {
					if (that.hand == 'left' && data2[7] == 1) {
						api.sendEvent({
							name: 'CHANGE_HAND',
							extra: {}
						});
						return;
					}
					if (that.hand == 'right' && data2[6] == 1) {
						api.sendEvent({
							name: 'CHANGE_HAND',
							extra: {}
						});
						return;
					}
				}

				// 判断左手操作 还是右手操作6	BLACK 7	RED
				if (data2[6] == 1 && !that.hand && ((data1[0] == 1 && that.isEnterTest) || that.switch_state == 'open')) {
					that.hand = 'left'
				}

				if (data2[7] == 1 && !that.hand && ((data1[0] == 1 && that.isEnterTest) || that.switch_state == 'open')) {
					that.hand = 'right'
				}



				// console.log('校验成功')
				if (isMicroscopic) {
					var typeName = i18n.get("microscopic.recognition") || '镜下识别';
					that.typeName = typeName;
					that.type = '0x00';
					// AA 00 01 01 AD 打开开关
					// AA 00 08 01 AD 结束开关
					// AA 00 00 03 AD 位置1有信号
					// AA 00 00 05 AD 位置2有信号
					// AA 00 00 09 AD 位置3有信号
					// AA 00 00 11 AD 位置4有信号
					// AA 00 00 21 AD 位置5有信号
					that.microscopic(data1, data2); //镜下识别
					that.hardware(); //获取当前科目
					return false;
				}
				switch (that.type) {
					case '0x01':
						var typeName = i18n.get("clamping.training") || '夹持训练';
						that.typeName = typeName;
						// AA 01 01 00 AC 打开开关
						// AA 01 02 00 2D 左侧投的红色球
						// AA 01 04 00 2D 左侧投的绿色球（错误）
						// AA 01 08 00 2D 右侧投的红色球（错误）
						// AA 01 10 00 2D 左侧投的绿色球
						// AA 01 80 00 2D 结束开关
						that.clamp(data1, data2); //夹持训练
						break;
					case '0x02':
						var typeName = i18n.get("positioning") || '定位摆放';
						that.typeName = typeName;
						// AA 02 01 00 AD 打开开关
						// AA 02 80 00 2E 结束开关
						// AA 02 02 00 AD 位置1有信号
						// AA 02 04 00 AD 位置2有信号
						// AA 02 08 00 AD 位置3有信号
						// AA 02 10 00 AD 位置4有信号
						// AA 02 20 00 AD 位置5有信号
						// AA 02 40 00 AD 位置6有信号
						that.ferrule(data1, data2); //定位摆放
						break;
					case '0x03':
						var typeName = i18n.get("pin.lead") || '飞跃龙门';
						that.typeName = typeName;
						// AA 03 01 00 AE 打开开关
						// AA 03 80 00 2F 结束开关
						// AA 03 02 00 BC 位置1有信号
						// AA 03 06 00 B3 位置2有信号
						// AA 03 0E 00 BB 位置3有信号
						// AA 03 1E 00 CB 位置4有信号
						// AA 03 3E 00 EB 位置5有信号
						// AA 03 7E 00 12B 位置6有信号
						that.thread(data1, data2); //飞跃龙门
						break;
					case '0x04':
						var typeName = i18n.get("shear.training") || '剪切训练';
						that.typeName = typeName;
						// AA 04 01 00 AF 打开开关
						// AA 04 80 00 30 结束开关
						// AA 04 02 00 B0 位置1有信号
						// AA 04 04 00 B2 位置2有信号
						that.shear(data1, data2); //剪切训练
						break;
					case '0x05':
						var typeName = i18n.get("suture.training") || '缝合训练';
						that.typeName = typeName;
						// AA 05 01 00 B0 打开开关
						// AA 05 80 00 31 结束开关
						// AA 05 02 00 BB 位置12有信号
						// AA 05 04 00 CD 位置34有信号  06
						// AA 05 08 00 133 位置56有信号 0e
						that.suture(data1, data2); //缝合训练
						break;
					default:
						break;
				}
			}
			that.hardware(); //获取当前科目
		},
		//十六进制转ASCII码
		hexCharCodeToStr: function hexCharCodeToStr(hexCharCodeStr) {
			var trimedStr = hexCharCodeStr.trim();
			var rawStr = trimedStr.substr(0, 2).toLowerCase() === "0x" ? trimedStr.substr(2) : trimedStr;
			var len = rawStr.length;
			if (len % 2 !== 0) {
				// alert("存在非法字符!");
				return "";
			}
			var curCharCode;
			var resultStr = [];
			for (var i = 0; i < len; i = i + 2) {
				curCharCode = parseInt(rawStr.substr(i, 2), 16);
				resultStr.push(String.fromCharCode(curCharCode));
			}
			return resultStr.join("");
		},
		// 镜下识别
		microscopic: function (data1, data2) {
			var that = this;
			// var data2 = String(data2).split('');
			// console.log('镜下识别')
			var animationData = {
				switch_state: that.switch_state, //开关 wait等待 open开始 close 结束
				type: 'microscopic', //镜下识别
				data: null, //数据动画判断
				rightNum: null, //正确个数
			};
			// console.log('data1.....' + JSON.stringify(data1))
			// console.log('data2.....' + JSON.stringify(data2))
			// 开始训练
			// if(data1[0] == 1){
			if (data1[0] == 1 && that.isEnterTest) {
				that.switch_state = 'open';
				animationData.switch_state = 'open';
				if (!that.startTime) {
					that.startTime = Date.parse(new Date()) / 1000; //开始时间
				}
			}
			// 结束训练
			that.endTime = Date.parse(new Date()) / 1000; //结束时间
			if (that.switch_state != 'open') {
				// 未开始考试
				return false;
			}
			// || (that.endTime - that.startTime) >= 90
			if (data1[7] == 1) {
				that.switch_state = 'close';
				animationData.switch_state = 'close';
				that.countScore(); //计算得分
			} else {
				for (var i = 0; i < 5; i++) {
					if (data2[i + 1] == 1) {
						that.mirrorSuccess[i] = 1;
					}
				}
				let rightNum = 0;
				let rightIndex = 0;
				for (var i = 0; i < that.mirrorSuccess.length; i++) {
					if (that.mirrorSuccess[i] == 1) {
						rightNum = rightNum + 1
					} else {
						rightIndex = i;
						break;
					}
				}
				for (var i = rightIndex; i < that.mirrorSuccess.length; i++) {
					that.mirrorSuccess[i] = 0;
				}
				animationData.rightNum = rightNum;
				animationData.data = data2;
			}
			// 发送数据处理动画
			// console.log('animationData+microscopic:'+JSON.stringify(animationData))
			api.sendEvent({
				name: 'animation',
				extra: {
					animationData: animationData
				}
			});
			// }
		},
		// 夹持训练
		clamp: function (data1, data2) {
			// 计时30秒优秀40分，45秒良好35分，1分钟及格30分，一分钟后每超3秒扣5分，1分30秒结束计时；计数满分20个60分，每少1个扣5分，总分100。
			var that = this;
			// console.log('夹持训练')
			// 监听球数据
			api.addEventListener({
				name: 'ball'
			}, function (ret, err) {
				var redBall = ret.value.redBall;
				var greenBall = ret.value.greenBall;
				that.metalBall = Number(redBall);
				that.plasticBall = Number(greenBall);
			});
			var animationData = {
				switch_state: that.switch_state, //开关 wait等待 open开始 close 结束
				type: 'clamp', //夹持训练
				data: null, //数据动画判断
			};
			// console.log('data1.....' + JSON.stringify(data1))
			// console.log('data2.....' + JSON.stringify(data2))
			// 开始训练
			if (data1[0] == 1 && that.isEnterTest) {
				that.switch_state = 'open';
				animationData.switch_state = 'open';
				if (!that.startTime) {
					that.startTime = Date.parse(new Date()) / 1000; //开始时间
				}
			}
			// 结束训练
			that.endTime = Date.parse(new Date()) / 1000; //结束时间
			if (that.switch_state != 'open') {
				// 未开始考试
				return false;
			}
			if (data1[7] == 1) {
				// console.log('考试结束去计算分.....' + JSON.stringify(animationData))
				that.switch_state = 'close';
				animationData.switch_state = 'close';
				that.countScore(); //计算得分
			} else {
				animationData.data = data1;
				// 左侧红色检测信号  右侧绿色检测信号
				// if (data1[1] == 1) {
				// 	// 左侧红色检测信号
				// 	if(that.metalBallCensus){
				// 		that.metalBallCensus = false;
				// 		that.metalBall = that.metalBall + 1;
				// 		setTimeout(function(){
				// 			that.metalBallCensus = true;
				// 		},200)
				// 	}
				// }
				// if (data1[4] == 1 && that.metalBall >= 10) {
				// 	//右侧绿色检测信号
				// 	if(that.ballCensus){
				// 		that.ballCensus = false;
				// 		that.plasticBall = that.plasticBall + 1;
				// 		setTimeout(function(){
				// 			that.ballCensus = true;
				// 		},200)
				// 	}
				// }
			}
			// 发送数据处理动画
			api.sendEvent({
				name: 'animation',
				extra: {
					animationData: animationData
				}
			});


		},
		// 定位摆放
		ferrule: function (data1, data2) {
			// 计时30秒优秀40分，45秒良好35分，1分钟及格30分，一分钟后每超3秒扣5分，1分30秒结束计时；计数满分20个60分，每少1个扣5分，总分100。
			var that = this;
			var animationData = {
				switch_state: that.switch_state, //开关 wait等待 open开始 close 结束
				type: 'ferrule', //定位摆放
				isError: that.isError, //是否有错
				rightNum: that.rightNum, //正确几个
				data: null, //数据动画判断
			};

			// 开始训练
			// 判断能否正常开始
			// console.log('numnumnumnum:'+that.rightNum)
			// console.log('numnumnumnum:'+animationData.rightNum)
			// console.log('numnumnumnum:'+num)

			// console.log('定位摆放data1'+JSON.stringify(data1))

			if (data1[0] == 1 && that.isEnterTest) {
				that.switch_state = 'open';
				animationData.switch_state = 'open';
				animationData.isError = false;
				that.isError = false;
				if (!that.startTime) {
					that.startTime = Date.parse(new Date()) / 1000; //开始时间
				}
			} else if (animationData.switch_state != 'open') {
				animationData.isError = true;
				that.isError = true;
			}
			// console.log('定位摆放11111111111')
			if (that.switch_state != 'open') {
				// 未开始考试
				return false;
			}
			// 结束训练
			that.endTime = Date.parse(new Date()) / 1000; //结束时间
			if (data1[7] == 1) {
				that.switch_state = 'close';
				animationData.switch_state = 'close';
				that.countScore(); //计算得分
			} else {
				// 判断正确个数
				let rightNum = 0;
				for (var i = 0; i < that.mSuccess.length; i++) {
					if (that.mSuccess[i] == 1) {
						rightNum = rightNum + 1;
					} else {
						break;
					}
				}

				// console.log('定位摆放22222222')
				// 判断是否有错
				let errorNum = 0;
				for (var i = (rightNum + 1); i < 6; i++) {
					if (data1[i + 1] == 1) {
						errorNum = errorNum + 1;
					}
				}
				if (errorNum > 0) {
					that.isError = true;
				} else {
					that.isError = false;
				}
				animationData.rightNum = rightNum;
				that.rightNum = rightNum;
				if (!that.isError) {
					for (var i = rightNum; i < 6; i++) {
						if (data1[i + 1] == 1) {
							that.mSuccess[i] = 1;
						}
					}
					let allRightNum = 0;
					for (var i = 0; i < that.mSuccess.length; i++) {
						if (that.mSuccess[i] == 1) {
							allRightNum++;
						} else {
							break;
						}
					}
					animationData.rightNum = allRightNum;
					that.rightNum = allRightNum;
				}
				animationData.data = data1;

				// console.log('定位摆放3333'+JSON.stringify(animationData))
			}
			// 发送数据处理动画
			api.sendEvent({
				name: 'animation',
				extra: {
					animationData: animationData
				}
			});
		},
		// 飞跃龙门
		thread: function (data1, data2) {
			// 20240229
			// 计时30秒优秀40分，45秒良好35分，1分钟及格30分，一分钟后每超3秒扣5分，1分30秒结束计时；计数满6个60分，每少1个扣15分，总分100。

			// 操作质量评价：计数满2次（往返）60分，每少1个扣30分；另触碰错误（金属环触碰到“S”形弯道）每一次扣15分；
			// 操作时间评价： 计时≤30秒优秀40分，≤45秒良好35分，≤1分钟及格30分，一分钟后每超3秒扣5分，1分30秒结束计时；（区间内得分计算到小数点后1位）

			var that = this;
			// console.log('飞跃龙门')
			var animationData = {
				switch_state: that.switch_state, //开关 wait等待 open开始 close 结束
				type: 'thread', //飞跃龙门
				isError: false, //是否有错
				data: null, //数据动画判断
			};
			// 开始训练
			// if(data1[0] == 1){
			if (data1[0] == 1 && that.isEnterTest) {
				that.switch_state = 'open';
				animationData.switch_state = 'open';
				if (!that.startTime) {
					that.startTime = Date.parse(new Date()) / 1000; //开始时间
				}
			}
			if (that.switch_state != 'open') {
				// 未开始考试
				return false;
			}
			// 结束训练
			that.endTime = Date.parse(new Date()) / 1000; //结束时间
			// || (that.endTime - that.startTime) >= 90
			if (data1[7] == 1) {
				// console.log('考试结束去计算分.....' + JSON.stringify(animationData))
				that.switch_state = 'close';
				animationData.switch_state = 'close';
				that.countScore(); //计算得分
			} else {
				// 6根柱子依次穿过20240229
				// for (var i = 0; i < data1.length; i++) {
				// 	if (data1[i+1] == 1) {
				// 		that.mSuccess[i] = 1;
				// 	}else{
				// 		that.mSuccess[i] = 0;
				// 	}
				// }
				animationData.data = data1;
				animationData.data2 = data2;
				if (data1[1] == 1 && that.threadTrigger) {
					that.mSuccess[0] = 1;
				}
				if (data1[2] == 1) {
					that.threadTrigger = true;
					that.mSuccess[1] = 1;
				}
				// 触碰铁丝
				if (data1[3] == 1 && !that.threadError && (data2[6] == 1 || data2[7] == 1)) {
					that.threadError = true;
					//左手移圈触碰铁丝次数
					if (data2[6] == 1) {
						that.leftErrorTimes++
					}
					//右手移圈触碰铁丝次数
					if (data2[7] == 1) {
						that.rightErrorTimes++
					}
					that.errorTimes++

					// 错10次结束考试
					if (that.errorTimes >= 10) {
						that.countScore(); //计算得分
					}

					setTimeout(function () {
						that.threadError = false;
					}, 300)
				}
			}
			animationData.threadError = that.threadError;
			// 发送数据处理动画
			api.sendEvent({
				name: 'animation',
				extra: {
					animationData: animationData
				}
			});
			// }
		},
		// 剪切训练
		shear: function (data1, data2) {
			// 计时45秒优秀40分，1分钟良好35分，1分30秒及格30分，一分钟后每超3秒扣5分，2分钟结束计时；无报错 计数满分60分，每报错1次扣20分，报错4次为0分，总分100。
			var that = this;
			var animationData = {
				switch_state: that.switch_state, //开关 wait等待 open开始 close 结束
				type: 'shear', //剪切训练
				data: null, //数据动画判断
			};
			// 开始训练
			// if(data1[0] == 1){
			if (data1[0] == 1 && that.isEnterTest) {
				that.switch_state = 'open';
				animationData.switch_state = 'open';
				if (!that.startTime) {
					that.startTime = Date.parse(new Date()) / 1000; //开始时间
				}
			}

			if (that.switch_state != 'open') {
				// 未开始考试
				return false;
			}
			// 结束训练
			that.endTime = Date.parse(new Date()) / 1000; //结束时间
			// || (that.endTime - that.startTime) >= 120
			if (data1[7] == 1) {
				// console.log('考试结束去计算分.....' + JSON.stringify(animationData))
				that.switch_state = 'close';
				animationData.switch_state = 'close';
				that.countScore(); //计算得分
			} else {
				animationData.data = data1;
				// 有剪切超界信号
				if (data1[1] == 1 || data1[2] == 1) {
					if (that.shearcensus) {
						that.shearcensus = false;
						that.successNum = that.successNum + 1;
					}
				} else {
					that.shearcensus = true
				}
				// 错4次结束考试
				if (that.successNum >= 4) {
					that.countScore(); //计算得分
				}
			}
			// 发送数据处理动画
			api.sendEvent({
				name: 'animation',
				extra: {
					animationData: animationData
				}
			});
			// }
		},
		// 缝合训练
		suture: function (data1, data2) {
			// 计时1分30秒优秀40分，2分钟良好35分，2分30秒及格30分，一分钟后每超15秒扣5分，3分钟结束计时； 计数满3个60分，每少1个扣20分，总分100。
			var that = this;
			var animationData = {
				switch_state: that.switch_state, //开关 wait等待 open开始 close 结束
				type: 'suture', //缝合训练
				data: null, //数据动画判断
				isError: that.isError, //是否有错
				rightNum: that.rightNum, //正确几个
				isOrder: that.isOrder,//是否按顺序判断
			};
			// 开始训练
			// if(data1[0] == 1){
			if (data1[0] == 1 && that.isEnterTest) {
				that.switch_state = 'open';
				animationData.switch_state = 'open';
				if (!that.startTime) {
					that.startTime = Date.parse(new Date()) / 1000; //开始时间
				}
			}
			if (that.switch_state != 'open') {
				// 未开始考试
				return false;
			}
			// 结束训练
			that.endTime = Date.parse(new Date()) / 1000; //结束时间
			if (data1[7] == 1) {
				// console.log('考试结束去计算分.....' + JSON.stringify(animationData))
				that.switch_state = 'close';
				animationData.switch_state = 'close';
				that.countScore(); //计算得分
			} else {
				// 缝合3个位置
				// 判断正确个数
				if (that.isOrder) {
					// 有顺序
					let rightNum = 0;
					for (var i = 0; i < 3; i++) {
						if (that.mSuccess[i] == 1) {
							rightNum = rightNum + 1;
						} else {
							break;
						}
					}
					// 判断是否有错
					let errorNum = 0;
					for (var i = (rightNum + 1); i < 7; i++) {
						if (data1[i + 1] == 1) {
							errorNum = errorNum + 1;
						}
					}
					if (errorNum > 0) {
						that.isError = true;
					} else {
						that.isError = false;
					}
					if (!that.isError) {
						// console.log('rightNum'+rightNum)
						// console.log('data1'+JSON.stringify(data1))
						for (var i = 0; i < 3; i++) {
							if (data1[i + 1] == 1) {
								that.mSuccess[i] = 1;
							} else {
								that.mSuccess[i] = 0;
							}
						}
						let allRightNum = 0;
						for (var i = 0; i < 3; i++) {
							if (that.mSuccess[i] == 1) {
								allRightNum = allRightNum + 1
							} else {
								break;
							}
						}
						// console.log('that.mSuccess'+JSON.stringify(that.mSuccess))
						animationData.rightNum = allRightNum;
						that.rightNum = allRightNum;
						// console.log('allRightNum'+allRightNum)

						if (data1[1] == 1 && data1[2] == 1) {
							that.isOrder = false;
						}
					}
				} else {
					// 无顺序
					for (var i = 0; i < 3; i++) {
						if (data1[i + 1] == 1) {
							that.mSuccess[i] = 1
						} else {
							that.mSuccess[i] = 0
						}
					}
				}
				animationData.data = data1;
			}
			// 发送数据处理动画
			api.sendEvent({
				name: 'animation',
				extra: {
					animationData: animationData
				}
			});
		},
		// 计算得分 
		countScore: function () {
			var that = this;
			var successNum = 0;
			var operateScore = 0; //操作得分
			var timeScore = 0; //时间得分
			var is_zero = ''; //是否总分是否为0
			// 时间得分计算
			var useTime = that.useTimes || that.endTime - that.startTime;
			// console.log('that.useTimes:'+that.useTimes)
			// '0x00':镜下识别 '0x01':夹持训练 '0x02':定位摆放 '0x03':飞跃龙门 '0x04':剪切训练 '0x05':缝合训练
			// 计时≤30秒为优秀满分为40分，≤45秒为良好35分，≤1分钟及格30分，一分钟后每超3秒扣5分，1分30秒结束计时结束；（区间内得分计算到小数点后1位）
			if (that.type == '0x00' || that.type == '0x01' || that.type == '0x02') {
				if (useTime <= 30) {
					timeScore = 40;
				} else if (useTime <= 45) {
					timeScore = useTime == 45 ? 35 : (40 - (useTime - 30) * 5 / 15).toFixed(1);
				} else if (useTime <= 60) {
					timeScore = useTime == 60 ? 30 : (35 - (useTime - 45) * 5 / 15).toFixed(1);
				} else if (useTime <= 90) {
					timeScore = 30 - parseInt((useTime - 60) / 3) * 5 > 0 ? 30 - parseInt((useTime - 60) / 3) * 5 : 0;
				} else {
					timeScore = 0;
				}
			} else if (that.type == '0x03') {
				// 飞跃龙门
				// 计时600s 共40分 5分一个时间段均分   分8个时间段 每个时间段75s
				// 整数部分
				let integerPart = Math.floor(useTime / 75);
				// 余数部分
				let remainder = useTime % 75;
				if ((integerPart == 7 && remainder > 0) || integerPart > 7) {
					timeScore = 0
				} else {
					timeScore = 40 - integerPart * 5;
				}
			} else if (that.type == '0x04') {
				// 剪切训练
				// 计时≤45秒优秀40分，≤1分钟良好35分，≤1分30秒及格30分，一分钟后每超3秒扣5分，2分钟结束计时；（区间内得分计算到小数点后1位）
				if (useTime <= 45) {
					timeScore = 40;
				} else if (useTime <= 60) {
					timeScore = useTime == 60 ? 35 : (40 - (useTime - 45) * 5 / 15).toFixed(1);
				} else if (useTime <= 90) {
					timeScore = useTime == 90 ? 30 : (35 - (useTime - 60) * 5 / 30).toFixed(1);
				} else if (useTime <= 120) {
					timeScore = 30 - parseInt((useTime - 90) / 3) * 5 > 0 ? 30 - parseInt((useTime - 90) / 3) * 5 : 0;
				} else {
					timeScore = 0;
				}
			} else if (that.type == '0x05') {
				// 缝合训练
				if (useTime <= 90) {
					timeScore = 40;
				} else if (useTime <= 120) {
					timeScore = useTime == 120 ? 35 : (40 - (useTime - 90) * 5 / 30).toFixed(1);
				} else if (useTime <= 150) {
					timeScore = useTime == 150 ? 30 : (35 - (useTime - 120) * 5 / 30).toFixed(1);
				} else if (useTime <= 180) {
					timeScore = 30 - parseInt((useTime - 150) / 5) * 5 > 0 ? 30 - parseInt((useTime - 150) / 5) * 5 : 0;
				} else {
					timeScore = 0;
				}
			}
			// 避免计算精度失真
			if (String(timeScore).length > 7) {
				timeScore = timeScore.toFixed(1);
			}
			// 操作计数得分
			if (that.type == '0x00') {
				// '0x00':镜下识别
				for (var i = 0; i < that.mirrorSuccess.length; i++) {
					successNum += that.mirrorSuccess[i]; //操作成功数
				}
				if (successNum >= 5) {
					operateScore = 60
				} else {
					operateScore = 60 - (5 - successNum) * 20 > 0 ? 60 - (5 - successNum) * 20 : 0;
				}
			} else if (that.type == '0x02') {
				// '0x02':定位摆放 
				//满分60分，根据考生完成全部所完成技术要求进行评分：完成6个（60分）；完成5个（50分）；完成4个（40分）；完成3个（30分）；完成2个（20分）；完成1个（10分）；完成0个（0分）
				for (var i = 0; i < that.mSuccess.length; i++) {
					successNum += that.mSuccess[i]; //操作成功数
				}
				if (successNum >= 6) {
					operateScore = 60
				} else {
					operateScore = 60 - (6 - successNum) * 15 > 0 ? 60 - (6 - successNum) * 15 : 0;
				}
			} else if (that.type == '0x03') {
				//  '0x03':飞跃龙门
				//计数满2次（往返）60分，每少1个扣30分；另触碰错误（金属环触碰到“S”形弯道）0次（60分）；触碰错误1次（扣6分）；触碰错误≥10次（0分）
				for (var i = 0; i < that.mSuccess.length; i++) {
					successNum += that.mSuccess[i]; //操作成功数
				}
				if (successNum >= 2) {
					operateScore = 60
				} else {
					operateScore = 60 - (2 - successNum) * 30 > 0 ? 60 - (2 - successNum) * 30 : 0;
				}
				operateScore = operateScore - that.errorTimes * 6 > 0 ? operateScore - that.errorTimes * 6 : 0;
			} else if (that.type == '0x05') {
				// 缝合训练 
				//满分60分，根据考生完成全部所完成技术要求进行评分：完成3个（60分）；完成2个（40分）；完成1个（20分）；完成0个（0分）
				for (var i = 0; i < that.mSuccess.length; i++) {
					successNum += that.mSuccess[i]; //操作成功数
				}
				// 计算操作得分
				if (successNum >= 3) {
					operateScore = 60
				} else {
					operateScore = 60 - (3 - successNum) * 20 > 0 ? 60 - (3 - successNum) * 20 : 0;
				}
			} else if (that.type == '0x01') {
				// 夹持训练
				operateScore = 0;
				var metalBall = that.metalBall > 10 ? 10 : that.metalBall; //金属球成功个数
				var plasticBall = that.plasticBall > 10 ? 10 : that.plasticBall; //塑料球成功个数
				var ballAll = metalBall + plasticBall;//成功总数
				// console.log(metalBall,'metalBall')
				// console.log(plasticBall,'plasticBall')
				// console.log(ballAll,'ballAll')
				// 计算操作得分
				// 满分60分，根据考生完成全部所完成技术要求进行评分：10颗金属球，10颗塑料球（60分）；10颗金属球，5~9颗塑料球（50分）；10颗金属球，1~4颗塑料球（40分）；10颗金属球，0颗塑料球（30分）；5~9颗金属球，0颗塑料球（20分）；1~4颗金属球，0颗塑料球（10分）；0颗金属球，0颗塑料球（0分）
				if (ballAll >= 20) {
					operateScore = 60
				} else if (ballAll < 10) {
					operateScore = 0;
				} else {
					operateScore = 60 - (20 - ballAll) * 5 > 0 ? 60 - (20 - ballAll) * 5 : 0;
				}
			} else if (that.type == '0x04') {
				// 剪切训练 满分60分，根据考生完成全部所完成技术要求进行评分：剪切错误0次（60分）；剪切错误1次（45分）；剪切错误2次（30分）；剪切错误3次（15分）；剪切错误≥4次（0分）
				successNum = that.successNum; //操作失败数
				// console.log('剪切训练successNum:'+successNum)
				// 计算操作得分
				if (useTime >= 150 || successNum >= 4) {
					// 超过时间和总共错的次数
					operateScore = 0;
					timeScore = 0;
					is_zero = 1;
				} else if (successNum == 0) {
					operateScore = 60
				} else {
					operateScore = 60 - successNum * 20 > 0 ? 60 - successNum * 20 : 0;
				}
			}
			//弹窗显示数据
			var testData = {
				hand: that.hand,
				useTime: useTime, //操作时间秒
				operateScore: operateScore, //操作得分
				timeScore: timeScore, //时间得分
				allScore: (operateScore + timeScore), //总得分
				is_zero: is_zero,
				errorTimes: that.errorTimes,
				leftErrorTimes: that.leftErrorTimes,
				rightErrorTimes: that.rightErrorTimes,
				type: that.type,
			};
			// console.log('考试得分.....' + JSON.stringify(testData))
			// 考试结束
			api.sendEvent({
				name: 'TEST_OVER',
				extra: {
					testData: testData
				}
			});

			that.endTime = 0; //重置时间
			that.startTime = 0; //重置时间
			that.successNum = 0;
			that.metalBall = 0;
			that.plasticBall = 0;
			that.shearcensus = true;
			that.errorTimes = 0;
			that.leftErrorTimes = 0;//左手移圈触碰铁丝次数
			that.rightErrorTimes = 0;//右手移圈触碰铁丝次数
			that.mSuccess = [0, 0, 0, 0, 0, 0];
			// 重置数据
			that.resetData();
		},

		// 获取当前用户可参加考试的科目
		getExam: function (obj) {
			var that = this;
			APP.r.get({
				api: 'exam/get_now_exam',
				params: {
					category_id: that.categoryId
				},
				success: function (res) {
					that.examData = res.data;
					let msg = i18n.get("registered.exam") || '未报名考试，请先报名';
					if (!res.data.length) {
						API.errorToast(res.msg);
						return false;
					} else if (res.data.length == 1) {
						that.examId = res.data[0].id;
					} else if (res.data.length > 1) {
						that.examId = res.data[0].id;
					}
					obj.success();
				}
			});
		},
		// 获取分类
		getCategoryList: function () {
			var that = this;
			APP.r.get({
				api: 'category/get_list',
				params: {},
				success: function (res) {
					that.subject = res.data;
					var _data = res.data;
					var _html = "";
					try {
						that.videoCategoryId = _data[0].id;
						for (var i = 0; i < _data.length; i++) {
							_html +=
								`<li class = "${i == 0 ? 'active' : ' '} " data-id = "${_data[i].id}" >${_data[i].category}</li>`;
						}
					} catch (e) {
						//TODO handle the exception
					}
					$('#nav-box').html(_html);
					that.getVideoList();
					that.rules(); //重新规则相关内容
				}
			});
		},
		// 获取视频
		getVideoList: function () {
			var that = this;
			let params = {
				page: 1,
				limit_num: 1,
				category: that.videoCategoryId,
			}
			APP.r.get({
				api: 'video/get_list',
				params: params,
				success: function (res) {
					if (res.data.data.length > 0) {
						that.videoObj = res.data.data[0];
						var imgHost = Config.imgHost;
						var _html = `<video  controlsList="nodownload" class="video-js" controls playsinline preload="auto" style="object-fit:contain;"  poster=" ${imgHost + res.data.data[0].image_url}" data-setup="{}">
								<source src="${res.data.data[0].video_url}" type="video/mp4">
								<p class="vjs-no-js"> To view this video please enable JavaScript, and consider upgrading to a web browser that <a href="${res.data.data[0].video_url}" target="_blank">supports HTML5 video</a> </p>
							</video>`;
						$('.index-video').html(_html);
					} else {
						var _html = `<video class="video-js" controls playsinline preload="auto" style="object-fit:contain;"  poster="" data-setup="{}">
							<source src="" type="video/mp4">
							<p class="vjs-no-js"> To view this video please enable JavaScript, and consider upgrading to a web browser that <a href="" target="_blank">supports HTML5 video</a> </p>
						</video>`;
						$('.index-video').html(_html);
					}
				}
			});
		},
		// 获取最新考试信息
		getNewestExamLog: function () {
			var that = this;
			APP.r.get({
				api: 'exam/get_newest_exam_log',
				params: {
					limit_num: 6
				},
				success: function (res) {
					var _data = res.data;
					// console.log('_data',JSON.stringify(_data))
					// 是否通过 0进行中 1通过 2未通过
					var _html = "";
					let txt1 = i18n.get("preparing") || '准备中';
					let txt2 = i18n.get("passed") || '已通过';
					let txt3 = i18n.get("failed") || '不通过';
					try {
						for (var i = 0; i < _data.length; i++) {
							_html +=
								`<li class="${_data[i].is_pass == 0 ? 'status3' : _data[i].is_pass == 1 ? 'status1' : 'status2'}"><span>${_data[i].category_name}</span><i>${_data[i].is_pass_text}</i></li>`;
						}
					} catch (e) {
						//TODO handle the exception
					}
					$('#test-box').html(_html);
				}
			});
		},
		//退出方法
		exitBtn: function () {
			var that = this;

			that.closeSocket();
			that.close();
			api.removePrefs({
				key: Config.Key.userinfo
			});
			api.removePrefs({
				key: Config.Key.user_token
			});
			let toast = i18n.get("log.out") || '退出登录成功';
			API.errorToast(toast, function () {
				// APP.w.openWin('public_login');
				api.closeToWin({
					name: 'root'
				});
			});
			// APP.r.post({
			// 	api: 'user/logout',
			// 	params: {},
			// 	success: function(res) {
			// 		API.errorToast("退出登录成功",function(){
			// 			APP.w.openWin('public_login');
			// 		});
			// 		api.removePrefs({key: Config.Key.userinfo});
			// 		api.removePrefs({ key: Config.Key.user_token});
			// 		// API.sendEvt('LOGOUT');
			// 	}
			// });
		},
		// 获取用户信息
		getUserinfo: function () {
			var that = this;
			var user = JSON.parse(USER.getUserinfo());
			that.userInfo = user;
			var _html = `<img src="${Config.imgHost + user.avatar}" alt="">
				<div class="txt">
					<div class="name">${user.nickname}</div>
					<div class="tel">${user.mobile}</div>
				</div>`;
			$('#user').html(_html);
		},
		// 获取硬件科目
		hardware: function () {
			var that = this;
			var sign = that.type; //通过设备获取标志
			// console.log('sign.....' + sign)
			// console.log('subject.....'+ JSON.stringify(that.subject))

			let txt = i18n.get("examination.subjects") || '考试科目';
			for (var i = 0; i < that.subject.length; i++) {
				if (that.subject[i].sign == sign) {
					that.categoryId = that.subject[i].id;
					var _name = "";
					var _html = `${txt}: <span> ${that.subject[i].category}</span>`
					$('.section .test').html(_html);
					break;
				}
			}
		},
		// 获取考试规则相关内容
		rules: function () {
			var that = this;
			let txt1 = i18n.get("examiner.instructions") || '考官指令';
			let txt2 = i18n.get("comprehensive.evaluation") || '综合评价';
			let txt3 = i18n.get("operation.quality.evaluation") || '操作质量评价';
			let txt4 = i18n.get("operation.time.evaluation") || '操作时间评价';
			let txt5 = i18n.get("operation.instructions") || '操作说明';
			let params = {
				category_id: that.videoCategoryId,
			}
			APP.r.get({
				api: 'category/get_info',
				params: params,
				success: function (res) {
					var _html = `<div class="box-lis">
									<div class="name">${txt1}：</div>
									<div class="text">${res.data.instructions}</div>
								</div>
								<div class="box-lis">
									<div class="name">${txt2}：</div>
									<div class="text">${res.data.overall_merit}</div>
								</div>
								<div class="box-lis">
									<div class="name">${txt3}：</div>
									<div class="text">${res.data.operate_rule}</div>
								</div>
								<div class="box-lis">
									<div class="name">${txt4}：</div>
									<div class="text">${res.data.time_rule}</div>
								</div>
								<div class="box-lis">
									<div class="name">${txt5}：</div>
									<div class="text">${res.data.operate_explain}</div>
								</div>`;
					$('.box-con').html(_html);
				}
			});
		},
		// 16进制转二进制
		transform: function (num) {
			var that = this;
			return parseInt(num, 16).toString(2)
		},

	}
}
API.run(page);
